package belf.migrate.engine.job;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
public class Result<T> {

    private T data;

    private int code;

    private String msg;

    private static final String MSG_SUCCESS = "操作成功！";
    private static final String MSG_FAIL = "操作失败！";

    public static <T> Result<T> by(Result<?> result) {
        return by(result, null);
    }
    public static <T> Result<T> by(Result<?> result, T body) {
        return new Result<>(body, result.getCode(), result.getMsg());
    }

    public static <T> Result<T> of(Boolean b, String msg) {
        return b != null && b ? Result.success(null, msg + "成功！") : Result.fail(msg + "失败！");
    }

    public static <T> Result<T> of(Boolean b) {
        return b != null && b ? Result.success() : Result.fail();
    }

    public static <T> Result<T> success(T body, String msg) {
        return new Result<>(body, CODE.SUCCESS.value, msg);
    }

    public static <T> Result<T> success(T body) {
        return success(body, MSG_SUCCESS);
    }

    public static <T> Result<T> success() {
        return success(null, MSG_SUCCESS);
    }

    public static <T> Result<T> fail(T body, String msg) {
        return new Result<>(body, CODE.FAIL.value, msg);
    }

    public static <T> Result<T> fail(String msg) {
        return new Result<>(null, CODE.FAIL.value, msg);
    }

    public static <T> Result<T> fail() {
        return fail(MSG_FAIL);
    }

    public static <T> Result<T> sqlFail(String msg) {
        return new Result<>(null, CODE.SQL_FAIL.value, msg);
    }

    public static <T> Result<T> by(CODE code, String msg) {
        return new Result<>(null, code.value, msg);
    }

    public static <T> Result<T> by(T body, CODE code, String msg) {
        return new Result<>(body, code.value, msg);
    }

    private Result(T data, int code, String msg) {
        this.data = data;
        this.code = code;
        this.msg = msg;
    }

    @AllArgsConstructor
    public enum CODE {
        SUCCESS(200),
        FAIL(500),

        SQL_FAIL(111),
        NOT_TOKEN(600),
        CONNECTION_FAIL(700),
        ;
        @Getter
        private final int value;
    }

    public boolean isSuccess() {
        return code == CODE.SUCCESS.value;
    }
}
